package com.njlime.member.service.app;

import com.njlime.cms.service.app.AppInformationService;
import com.njlime.core.helper.GlobalValue;
import com.njlime.core.helper.PageBean;
import com.njlime.core.sdk.wechat.WeChatUser;
import com.njlime.core.sdk.wechat.WeChatUtil;
import com.njlime.core.sdk.wechat.jsapi.AccessToken;
import com.njlime.core.utils.DateUtil;
import com.njlime.member.entiies.TMember;
import com.njlime.member.repository.app.AppMemberDao;
import com.njlime.sys.entities.ConfigItem;
import com.njlime.sys.entities.UnitWxConfig;
import com.njlime.sys.service.ConfigService;
import com.njlime.sys.service.UnitService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by Dean on 2017/10/9.
 */
@Service
public class AppMemberService {

    @Resource
    private AppMemberDao appMemberDao;
    @Resource
    private UnitService unitService;
    @Resource
    private ConfigService configService;
    @Resource
    private AppMemberFocusService appMemberFocusService;
    @Resource
    private AppInformationService appInformationService;

    /**
     * 保存
     * @param member
     */
    @Transactional(readOnly = false)
    public TMember save(TMember member){
        member.setRead_count(0);
        member.setLevel(1);
        member.setOrder_count(0);
        member.setOrder_money(0);
        member.setStatus(1);
        member.setCreate_time(DateUtil.dateFormat(new Date(),"yyyy-MM-dd HH:mm:ss"));
        member.setIs_del(GlobalValue.NO);
        member.setSex(0);
        return appMemberDao.save(member);
    }

    /**
     * 根据联系方式获取粉丝
     * @param mobile
     * @param unit_id
     * @return
     */
    public Map<String,Object> getUserByMobile(String mobile, Integer unit_id) {
        return appMemberDao.getUserByMobile(mobile, unit_id);
    }
    /**
     * 根据openid获取粉丝
     * @param openid
     * @return
     */
    public TMember getUserByOpenId(String openid) {
        return appMemberDao.getUserByOpenId(openid);
    }
    /**
     * 更新时间
     * @param id
     */
    @Transactional(readOnly = false)
    public void updateVipUpdateTime(Integer id) {
        appMemberDao.updateMemberUpdateTime(id);
    }


    /**
     * id 查找vip
     * @param id
     * @return
     */
    public Map<String,Object> getMemberById(Integer id){
        return appMemberDao.getMemberById(id);
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    public TMember findOne(Integer id){
        return appMemberDao.findOne(id);
    }

    /**
     * openid 查找vip
     * @param openid
     * @return
     */
    public Map<String,Object> getWithOpenId(String openid, Integer unit_id){
        return appMemberDao.getWithOpenId(openid, unit_id);
    }

    /**
     * id 修改vip
     * @param info
     * @return
     */
    @Transactional(readOnly = false)
    public int updateMember(TMember info){
        return appMemberDao.updateById(info);
    }

    /**
     * 更新openid
     * @param id
     * @param openid
     * @return
     */
    @Transactional(readOnly = false)
    public int updateOpenid(Integer id, String openid){
        return appMemberDao.updateOpenid(id, openid);
    }

    /**
     * 更新联系方式
     * @param id
     * @param mobile
     * @return
     */
    @Transactional(readOnly = false)
    public int updateMobile(Integer id, String mobile){
        return appMemberDao.updateMobile(id,mobile);
    }

    /**
     * 两个账号绑定
     * @param member
     * @param newMember
     */
    @Transactional
    public void bindMember(TMember member,TMember newMember){
        member.setOpenid(newMember.getOpenid());
        member.setName(newMember.getName());
        member.setNick_name(newMember.getNick_name());
        member.setWx(newMember.getWx());
        member.setHead_url(newMember.getHead_url());
        updateMember(member);
        appMemberDao.delete(newMember.getId());
    }

    /**
     * 更新tags
     * @param id
     * @param tags
     * @return
     */
    @Transactional(readOnly = false)
    public int updateTags(Integer id, String tags){
        return appMemberDao.updateTags(id,tags);
    }

    /**
     * 粉丝升级
     * @param member_id
     */
    @Transactional
    public void upgradeMember(Integer member_id){
        //判断是否满足升级条件
        Map<String,Object> vip = getMemberById(member_id);
        ConfigItem config = configService.getByName("vip_upgrade_condition", Integer.valueOf(vip.get("unit_id").toString()));
        Integer upgrade_num = Integer.parseInt(config.getConfig_value());
        Integer new_level = ((Integer)vip.get("read_count"))/upgrade_num + 1;
        Integer ori_level = 1;
        if(vip.get("level")!=null && !"".equals(vip.get("level").toString().trim())){
            ori_level = Integer.valueOf(vip.get("level").toString());
        }
        if(new_level - ori_level > 0 && new_level <= 24){
            upgradeMember(member_id,ori_level,new_level);
            //升级记录
            /*MemberUpgrade vu = new MemberUpgrade();
            vu.setVip_id(vip_id);
            vu.setVip_leve(new_level);
            vu.setCreate_time(new Date());
            vipUpgradeDao.save(vu);*/
        }
    }

    /**
     * vip升级
     */
    @Transactional
    public void upgradeMember(Integer vip_id,Integer ori_level,Integer new_level){
        appMemberDao.upgradeVip(vip_id,ori_level,new_level);
    }

    /**
     * 更新用户头像
     * @param sysId
     * @param pic
     */
    @Transactional
    public void updateUserPic(Integer sysId, String pic) {
        appMemberDao.updateUserPic(sysId,pic);

    }

    /**
     * 更新密码
     * @param mobile
     * @param password
     */
    @Transactional
    public void updatePsw(String mobile, Integer unit_id, String password) {
        appMemberDao.updatePsw(mobile, unit_id, password);
    }

    /**
     * 更新阅读数
     */
    @Transactional
    public void updateReadCount(Integer vip_id){
        appMemberDao.updateReadCount(vip_id);
    }

    /**
     * 更新订单数
     * @param vip_id
     */
    @Transactional
    public void updateOrderCount(Integer vip_id){
        appMemberDao.updateOrderCount(vip_id);
    }

    /**
     * 获取标签
     * @param unit_id
     * @return
     */
    public List<Map<String,Object>> labelGet(Integer unit_id){
        return appMemberDao.labelGet(unit_id);
    }


    /**
     * 微信粉丝
     * @param openId
     * @param unit_id
     * @return
     */
    @Transactional
    public Map<String,Object> getWechatMember(String openId,Integer unit_id){
        Map<String,Object> vip = getWithOpenId(openId, unit_id);
        if(vip == null){
            UnitWxConfig unitWxConfig = unitService.getWxConfig(unitService.getRootUnit(unit_id));
            AccessToken accessToken = WeChatUtil.getAccessToken(unitWxConfig.getApp_id(),unitWxConfig.getApp_secret());
            WeChatUser wu = WeChatUtil.getUserInfo(accessToken.getToken(), openId);
            TMember member = new TMember();
            if(wu!=null){
                if(wu.getNickname()!=null){
                    member.setName(wu.getNickname());
                    member.setNick_name(wu.getNickname());
                    member.setWx(wu.getNickname());
                }
                member.setSex(wu.getSex());
                member.setHead_url(wu.getHeadImgUrl());
            }
            member.setOpenid(openId);
            member.setUnit_id(unit_id);
            save(member);
            vip = getWithOpenId(openId, unit_id);
            updateVipUpdateTime(Integer.valueOf(vip.get("id").toString()));
        }
        return vip;
    }

    /**
     * 关注列表
     * @param pageBean
     * @param user_id
     * @return
     */
    public PageBean focusList(PageBean pageBean, int user_id){
        pageBean = appMemberFocusService.getByMemberId(pageBean,user_id);
        if(pageBean.getMapList() != null){
            PageBean infoPage = new PageBean(2);
            for(Map<String,Object> focus : pageBean.getMapList()){
                focus.put("focus", GlobalValue.YES);
                focus.put("list",appInformationService.authorList(infoPage,Integer.valueOf(focus.get("id").toString())).getMapList());
            }
        }
        return pageBean;
    }
}
